package com.jvtd.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jvtd.bean.LocalAddressBookBean;
import com.jvtd.bean.ProvincesBean;
import com.jvtd.rxjava.JvtdObserverSubscriber;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 获取联系人信息工具类
 */
public class LocalAddressBookUtils
{
  private static final String ICC_ADN = "content://icc/adn";
  private static final String SIM_ADN = "content://sim/adn";

  private static volatile LocalAddressBookUtils instance;
  private final Context mContext;
  private boolean isGetSim = true;
  private List<LocalAddressBookBean> mAddressBookBeans;//本地通讯录信息
  private OnGetListener mOnGetListener;//回调

  public interface OnGetListener {
    void onGetSuccess(List<LocalAddressBookBean> addressBookBeans);

    void onGetFailed();
  }

  public static LocalAddressBookUtils getInstance(Context context) {
    if (instance == null)
      synchronized (LocalAddressBookUtils.class) {
        if (instance == null)
          instance = new LocalAddressBookUtils(context.getApplicationContext());
      }
    return instance;
  }

  private LocalAddressBookUtils(Context context) {
    mContext = context;
    isGetSim = true;
  }

  /**
   * 是否获取sim卡信息
   * @param getSim
   */
  public LocalAddressBookUtils setGetSim(boolean getSim) {
    isGetSim = getSim;
    return this;
  }

  /**
   * 设置回调
   * @param onGetListener
   * @return
   */
  public LocalAddressBookUtils setOnGetListener(OnGetListener onGetListener) {
    mOnGetListener = onGetListener;
    return this;
  }

  /**
   * 获取通讯录信息
   */
  public void getAllContacts()
  {
    if (mAddressBookBeans != null && mOnGetListener != null){
      mOnGetListener.onGetSuccess(mAddressBookBeans);
      return;
    }
    Observable.fromCallable(() -> {
      Boolean b = false;
      try{
        List<LocalAddressBookBean> list = new ArrayList<>();
        //得到ContentResolver对象
        ContentResolver cr = mContext.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //向下移动光标
        if (cursor != null) {
          while (cursor.moveToNext()) {
            //取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String contact = cursor.getString(nameFieldColumnIndex);

            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phoneCursor != null) {
              while (phoneCursor.moveToNext()) {
                LocalAddressBookBean info = new LocalAddressBookBean();
                info.setRemarks(contact);

                String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                //格式化手机号
                phoneNumber = phoneNumber.replaceAll("-", "").replaceAll(" ", "");
                info.setPhone(phoneNumber);
                // 添加集合
                list.add(info);
              }
              phoneCursor.close();
            }
          }
          cursor.close();
        }
        if (isGetSim){
          list.addAll(getSimAdnContact(mContext));
          list.addAll(getIccAdnContact(mContext));
        }
        mAddressBookBeans = new ArrayList<>(list);
        b = true;
      } catch (Exception e) {
        e.printStackTrace();
      }
      return b;
    }).compose(upstream -> upstream.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()))
            .subscribe(new JvtdObserverSubscriber<Boolean>(null) {
              @Override
              public void onNext(Boolean aBoolean) {
                if (mOnGetListener != null)
                  if (aBoolean) {
                    mOnGetListener.onGetSuccess(mAddressBookBeans);
                  } else {
                    mOnGetListener.onGetFailed();
                  }
              }

              @Override
              public void onError(Throwable e) {
                if (mOnGetListener != null) {
                  mOnGetListener.onGetFailed();
                }
              }
            });
  }

  /**
   * 获取sim adn手机号
   * @param context 上下文
   * @return 手机列表
   */
  private List<LocalAddressBookBean> getSimAdnContact(Context context) {
    return getSimContact(context,SIM_ADN);
  }

  /**
   * 获取 icc adn手机号
   * @param context 上下文
   * @return 手机列表
   */
  private List<LocalAddressBookBean> getIccAdnContact(Context context) {
    return getSimContact(context,ICC_ADN);
  }

  /**
   * 获取sim卡手机号
   * @param context 上下文
   * @param adn 位置信息  有2中
   * @return 手机列表
   */
  private List<LocalAddressBookBean> getSimContact(Context context, String adn) {
    List<LocalAddressBookBean> list = new ArrayList<>();
    // 读取SIM卡手机号,有两种可能:content://icc/adn与content://sim/adn
    Cursor cursor = null;
    try {
      Intent intent = new Intent();
      intent.setData(Uri.parse(adn));
      Uri uri = intent.getData();
      if (uri != null) {
        cursor = context.getContentResolver().query(uri, null,
                null, null, null);
      }
      if (cursor != null) {
        while (cursor.moveToNext()) {
          // 取得联系人名字
          int nameIndex = cursor.getColumnIndex("name");
          // 取得电话号码
          int numberIndex = cursor.getColumnIndex("number");
          String number = cursor.getString(numberIndex);
          if (isUserNumber(number)) {// 是否是手机号码
            LocalAddressBookBean sci = new LocalAddressBookBean();
            sci.setPhone(formatMobileNumber(number));
            sci.setRemarks(cursor.getString(nameIndex));
            list.add(sci);
          }
        }
        cursor.close();
      }
    } catch (Exception e) {
      if (cursor != null)
        cursor.close();
    }
    return list;
  }

  /**
   * 手机格式
   * @param num2 手机号
   * @return 正确手机号
   */
  private String formatMobileNumber(String num2) {
    String num;
    if (num2 != null) {
      // 有的通讯录格式为135-1568-1234
      num = num2.replaceAll("-", "");
      // 有的通讯录格式中- 变成了空格
      num = num.replaceAll(" ", "");
      if (num.startsWith("+86")) {
        num = num.substring(3);
      } else if (num.startsWith("86")) {
        num = num.substring(2);
      } else if (num.startsWith("86")) {
        num = num.substring(2);
      }
    } else {
      num = "";
    }
    // 有些手机号码格式 86后有空格
    return num.trim();
  }

  /**
   * 是否为手机号
   * @param num 手机号
   * @return 是否
   */
  private boolean isUserNumber(String num) {
    if (null == num || "".equalsIgnoreCase(num)) {
      return false;
    }
    boolean re = false;
    if (num.length() == 11) {
      if (num.startsWith("1")) {
        re = true;
      }
    }
    return re;
  }
}
